<template>
  <div class="dictionary-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>数据字典管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              新增字典
            </el-button>
            <el-button type="success" @click="showAddItemDialog">
              <el-icon><DocumentAdd /></el-icon>
              新增字典项
            </el-button>
            <el-button type="info" @click="exportDictionary">
              <el-icon><Download /></el-icon>
              导出字典
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="字典名称">
            <el-input v-model="searchForm.name" placeholder="请输入字典名称" clearable />
          </el-form-item>
          <el-form-item label="字典编码">
            <el-input v-model="searchForm.code" placeholder="请输入字典编码" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="启用" />
              <el-option label="禁用" value="禁用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 字典列表 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="字典名称" width="200" />
        <el-table-column prop="code" label="字典编码" width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="itemCount" label="字典项数量" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="handleViewItems(row)">
              字典项
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑字典对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="dictionaryFormRef"
        :model="dictionaryForm"
        :rules="dictionaryRules"
        label-width="100px"
      >
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="dictionaryForm.name" placeholder="请输入字典名称" />
        </el-form-item>
        
        <el-form-item label="字典编码" prop="code">
          <el-input v-model="dictionaryForm.code" placeholder="请输入字典编码" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="dictionaryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入字典描述"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dictionaryForm.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="dictionaryForm.sort" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 字典项管理对话框 -->
    <el-dialog
      v-model="itemsDialogVisible"
      :title="`${currentDictionary?.name} - 字典项管理`"
      width="800px"
    >
      <div class="items-header">
        <el-button type="primary" @click="showAddItemDialog">
          <el-icon><Plus /></el-icon>
          新增字典项
        </el-button>
      </div>
      
      <el-table :data="dictionaryItems" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="label" label="标签" width="150" />
        <el-table-column prop="value" label="值" width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="sort" label="排序" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditItem(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteItem(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增/编辑字典项对话框 -->
    <el-dialog
      v-model="itemDialogVisible"
      :title="itemDialogTitle"
      width="500px"
      @close="handleItemDialogClose"
    >
      <el-form
        ref="itemFormRef"
        :model="itemForm"
        :rules="itemRules"
        label-width="100px"
      >
        <el-form-item label="标签" prop="label">
          <el-input v-model="itemForm.label" placeholder="请输入标签" />
        </el-form-item>
        
        <el-form-item label="值" prop="value">
          <el-input v-model="itemForm.value" placeholder="请输入值" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="itemForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="itemForm.sort" :min="0" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="itemForm.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="itemDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleItemSubmit" :loading="itemSubmitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const itemsDialogVisible = ref(false)
const itemDialogVisible = ref(false)
const submitLoading = ref(false)
const itemSubmitLoading = ref(false)
const dictionaryFormRef = ref()
const itemFormRef = ref()

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  status: ''
})

// 字典表单
const dictionaryForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: '启用',
  sort: 0
})

// 字典项表单
const itemForm = reactive({
  id: null,
  dictionaryId: null,
  label: '',
  value: '',
  description: '',
  sort: 0,
  status: '启用'
})

// 表单验证规则
const dictionaryRules = {
  name: [
    { required: true, message: '请输入字典名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入字典编码', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const itemRules = {
  label: [
    { required: true, message: '请输入标签', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入值', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '用户状态',
    code: 'user_status',
    description: '用户账户状态字典',
    itemCount: 3,
    status: '启用',
    createTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    name: '订单状态',
    code: 'order_status',
    description: '订单状态字典',
    itemCount: 5,
    status: '启用',
    createTime: '2024-01-02 10:00:00'
  },
  {
    id: 3,
    name: '商品类别',
    code: 'product_category',
    description: '商品分类字典',
    itemCount: 8,
    status: '启用',
    createTime: '2024-01-03 10:00:00'
  },
  {
    id: 4,
    name: '支付方式',
    code: 'payment_method',
    description: '支付方式字典',
    itemCount: 4,
    status: '启用',
    createTime: '2024-01-04 10:00:00'
  }
])

// 当前字典
const currentDictionary = ref(null)

// 字典项数据
const dictionaryItems = ref([
  {
    id: 1,
    dictionaryId: 1,
    label: '正常',
    value: 'normal',
    description: '用户状态正常',
    sort: 1,
    status: '启用'
  },
  {
    id: 2,
    dictionaryId: 1,
    label: '禁用',
    value: 'disabled',
    description: '用户被禁用',
    sort: 2,
    status: '启用'
  },
  {
    id: 3,
    dictionaryId: 1,
    label: '锁定',
    value: 'locked',
    description: '用户被锁定',
    sort: 3,
    status: '启用'
  }
])

// 计算属性
const isEdit = computed(() => !!dictionaryForm.id)
const dialogTitle = computed(() => isEdit.value ? '编辑字典' : '新增字典')

const isItemEdit = computed(() => !!itemForm.id)
const itemDialogTitle = computed(() => isItemEdit.value ? '编辑字典项' : '新增字典项')

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    status: ''
  })
  handleSearch()
}

const showAddDialog = () => {
  dialogVisible.value = true
  resetForm()
}

const handleEdit = (row) => {
  dialogVisible.value = true
  Object.assign(dictionaryForm, { ...row })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该字典吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
      loadData()
    }
  } catch {
    // 用户取消删除
  }
}

const handleViewItems = (row) => {
  currentDictionary.value = row
  itemsDialogVisible.value = true
  loadDictionaryItems(row.id)
}

const loadDictionaryItems = (dictionaryId) => {
  // 模拟加载字典项数据
  dictionaryItems.value = dictionaryItems.value.filter(item => item.dictionaryId === dictionaryId)
}

const showAddItemDialog = () => {
  if (!currentDictionary.value) {
    ElMessage.warning('请先选择字典')
    return
  }
  itemDialogVisible.value = true
  resetItemForm()
}

const handleEditItem = (row) => {
  itemDialogVisible.value = true
  Object.assign(itemForm, { ...row })
}

const handleDeleteItem = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该字典项吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = dictionaryItems.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      dictionaryItems.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

const handleSubmit = async () => {
  if (!dictionaryFormRef.value) return
  
  try {
    await dictionaryFormRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      // 编辑字典
      const index = tableData.value.findIndex(item => item.id === dictionaryForm.id)
      if (index > -1) {
        tableData.value[index] = { ...dictionaryForm }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增字典
      const newDictionary = {
        ...dictionaryForm,
        id: Date.now(),
        itemCount: 0,
        createTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newDictionary)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleItemSubmit = async () => {
  if (!itemFormRef.value) return
  
  try {
    await itemFormRef.value.validate()
    itemSubmitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isItemEdit.value) {
      // 编辑字典项
      const index = dictionaryItems.value.findIndex(item => item.id === itemForm.id)
      if (index > -1) {
        dictionaryItems.value[index] = { ...itemForm }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增字典项
      const newItem = {
        ...itemForm,
        id: Date.now(),
        dictionaryId: currentDictionary.value.id
      }
      dictionaryItems.value.unshift(newItem)
      ElMessage.success('新增成功')
    }
    
    itemDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    itemSubmitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const handleItemDialogClose = () => {
  resetItemForm()
}

const resetForm = () => {
  Object.assign(dictionaryForm, {
    id: null,
    name: '',
    code: '',
    description: '',
    status: '启用',
    sort: 0
  })
  dictionaryFormRef.value?.clearValidate()
}

const resetItemForm = () => {
  Object.assign(itemForm, {
    id: null,
    dictionaryId: null,
    label: '',
    value: '',
    description: '',
    sort: 0,
    status: '启用'
  })
  itemFormRef.value?.clearValidate()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const exportDictionary = () => {
  ElMessage.success('字典导出成功')
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.dictionary-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.items-header {
  margin-bottom: 20px;
}
</style>
